package com.turing.sensivitycode.service;

import com.turing.common.entity.Context;
import com.turing.common.entity.UserToken;
import com.turing.sensivitycode.domain.SensivityCode;
import com.turing.sensivitycode.domain.SensivityCodeExample;
import com.turing.sensivitycode.mapper.SensivityCodeMapper;
import com.turing.sensivitycode.utils.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;


@Service
public class SensivityCodeService {

    private static final Logger logger = LoggerFactory.getLogger(SensivityCodeService.class);


    @Autowired
    private SensivityCodeMapper sensivityCodeMapper;


    @Value("file.path.store")
    private String filePath;


    /**
     * 针对指定的敏感词库来新增敏感词
     * @param sensivityCode 敏感词名称
     * @param lecId 敏感词库ID
     * @return
     */
    public String insertSensivityCode(String sensivityCode, Integer lecId) {
        UserToken tokenContext = Context.getTokenContext();
        // 创建人ID
        Integer userId = tokenContext.getUserId();
        String userName = tokenContext.getUserName();

        SensivityCode record = new SensivityCode();
        record.setCreatedTime(new Date());
        record.setCreatedBy(userName);
        record.setIsDel(0);
        record.setVersion(0);
        // 设置对应的表ID
        record.setLexcitionId(lecId);
        sensivityCodeMapper.insert(record);
        logger.info("插入成功");
        return "插入成功";
    }

    /**
     * 从Excel中将敏感词读取出来
     * @param lecId 敏感词词库ID名称
     * @param multipartFiles 上传的文件词库
     * @return
     */
    public String createSensivityCodeByExcel(Integer lecId,  MultipartFile[] multipartFiles) {

        logger.info("当前文件应存储在{}",filePath);
        File fileParent = new File(filePath);
        if (!fileParent.exists()){
            fileParent.mkdirs();
        }
        List<File> files = new ArrayList<>(multipartFiles.length);
        for (MultipartFile multipartFile : multipartFiles) {
            String originalFilename = multipartFile.getOriginalFilename();
            try {
                File tmpFile = new File(fileParent, originalFilename);
                multipartFile.transferTo(tmpFile);
                files.add(tmpFile);
            } catch (IOException e) {
                logger.error("上传的文件转File文件失败,对应的异常是：",e);
            }
        }
        Set<String> data = new HashSet<>();
        // 开始循环读取这里的Excel
        for (File file : files) {
            List<List<String>> lists = ExcelUtil.readExcel(file.getAbsolutePath());
            for (List<String> listOutSide : lists) {
                for (String element : listOutSide) {
                    data.add(element);
                }
            }
        }
        UserToken tokenContext = Context.getTokenContext();
        String userName = tokenContext.getUserName();
        // 开始来进行批量插入
        for (String datum : data) {
            SensivityCode record =  new SensivityCode();
            record.setDescription(datum);
            record.setCreatedTime(new Date());
            record.setIsDel(0);
            record.setLexcitionId(lecId);
            record.setCreatedBy(userName);
            record.setVersion(0);
            sensivityCodeMapper.insert(record);
        }
        logger.info("批量插入数据量:{}个",data.size());
        return "SUCCESS";
    }

    public List<SensivityCode> queryAllSensivityCodeByLecid(Integer lecId) {
        SensivityCodeExample example = new SensivityCodeExample();
        example.createCriteria().andIsDelEqualTo(0).andLexcitionIdEqualTo(lecId);
        return sensivityCodeMapper.selectByExample(example);
    }

    public String deleteSensivityCodeByLecIdAndSensivityCodeID(Integer sensivityCodeID, Integer lecId) {
        UserToken tokenContext = Context.getTokenContext();
        String userName = tokenContext.getUserName();
        SensivityCode record  = new SensivityCode();
        record.setId(sensivityCodeID);
        record.setUpdatedTime(new Date());
        record.setIsDel(1);
        record.setUpdatedBy(userName);
        SensivityCodeExample example = new SensivityCodeExample();
        example.createCriteria().andIsDelEqualTo(0).andLexcitionIdEqualTo(lecId);
        sensivityCodeMapper.updateByExampleSelective(record,example);
        return "SUCCESS";
    }
}
